﻿using System;
using System.Linq;
using System.Security;
using Peak.Core.DataInterfaces;
using System.Security.Principal;
using Peak.Core;

namespace Peak.ApplicationServices.Services
{
  public class TaskService : ITaskService
  {
    readonly ITaskRepository _taskRepository;
    private readonly IPrincipal _principal;

    public TaskService(ITaskRepository taskRepository, IPrincipal principal)
    {
      _taskRepository = taskRepository;
      _principal = principal;
    }

    public Task Get(int id)
    {
      Task task = _taskRepository.Get(id);
      if(task == null || task.Project.Users.FirstOrDefault(f=>f.UserName.ToLower()== _principal.Identity.Name.ToLower()) == null)
      {
        throw new EntityNotFoundException();
      }
      return task;
    }

    public Task Update(Task task)
    {
      if(task == null)
      {
        throw new ArgumentNullException("task");
      }
      if (task.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      return _taskRepository.SaveOrUpdate(task);
    }


    public Page<Task> GetPage(TaskFilter sf)
    {
      return _taskRepository.GetPage(sf);
    }


    public void Delete(Task task)
    {
      if (task == null)
      {
        throw new ArgumentNullException("task");
      }
      if (task.Project.Users.FirstOrDefault(f => f.UserName.ToLower() == _principal.Identity.Name.ToLower()) == null)
      {
        throw new SecurityException();
      }
      _taskRepository.Delete(task);
    }
  }
}
